<?php

require_once (dirname(__FILE__) . '/../prepend.php');
global $bdd;
global $logger;
/**
 * SEPA direct debit (SDD) message in XML format.
 */
require_once(dirname(__FILE__) . '/../inc/SEPA/class.SEPADirectDebitTransaction.php');
require_once(dirname(__FILE__) . '/../inc/SEPA/class.SEPAException.php');
require_once(dirname(__FILE__) . '/../inc/SEPA/class.SEPAGroupHeader.php');
require_once(dirname(__FILE__) . '/../inc/SEPA/class.SEPAMessage.php');
require_once(dirname(__FILE__) . '/../inc/SEPA/class.SEPAPaymentInfo.php');
require_once(dirname(__FILE__) . '/../inc/SEPA/class.URLify.php');
if ($_SESSION['niveauAuth']<>'0'){
$message = new SEPAMessage('urn:iso:std:iso:20022:tech:xsd:pain.008.001.02');
$groupHeader = new SEPAGroupHeader(); // (1..1)
$groupHeader->setMessageIdentification('SEPA-' . time()); // ID Unique
$groupHeader->setInitiatingPartyName(PRESTATAIRE_NOM); // Nom du crediteur
$message->setGroupHeader($groupHeader);

$paymentInfo = new SEPAPaymentInfo(); // (1..n)
$paymentInfo->setPaymentInformationIdentification('SEPA-' . time()); // ID Unique 
$paymentInfo->setBatchBooking('false');
$paymentInfo->setLocalInstrumentCode('CORE'); // Autres options: COR1, B2B
// Type et date
$seqType = 'FRST';
$days = 6;
if ($_GET['type'] == 'rcur'){
    $seqType = 'RCUR';
    $days = 3;
}

do{
    $days++;
    $collecDate = strtotime("+$days days");
}while (!isWorkableDay($collecDate));


$paymentInfo->setSequenceType($seqType);
// CORE: FRST: +6 days, RCUR: +3 days, FNAL: +3 days, OOFF: +6 days
// B2B: All +2 days
$paymentInfo->setRequestedCollectionDate(date( 'Y-m-d', $collecDate ));
// Account on which payment should be recieved
$paymentInfo->setCreditorName(PRESTATAIRE_NOM);
$paymentInfo->setCreditorAccountIBAN(IBAN);
$paymentInfo->setCreditorAgentBIC(BIC);
$paymentInfo->setCreditorSchemeIdentification(ICS);

//liste les factures
$q = "SELECT 
    SUM(af.total_facturation) AS total_facturation,
    fc.code_iban,
    fc.code_etablissement,
    fc.code_guichet,
    fc.num_compte,
    fc.rib,
    fc.code_client_hto,
    fc.raison_social,
    fc.swift,
    fc.nom
FROM
    fiche_client fc
    INNER JOIN
    admin_facture af ON fc.id = af.id_client
WHERE
    af.facture NOT LIKE '%temp%' AND fc.mode_paiement = 'Prélévement'
AND fc.nouveau_client is ";
if ($seqType === 'FRST') {
    $q .= "true";
} else {
    $q .= "false";
}
$q .= " GROUP BY fc.code_client_hto";
$q .= " ORDER BY id_client";

$requete = $bdd->prepare($q);
$requete->execute();
$results = $requete->fetchall(PDO::FETCH_ASSOC);

if (empty($results)) {
    $alert = array('message' => 'Aucune facture à ajouter au fichier SEPA', 'type' => 'warning');
    $_SESSION['alerts'][] = $alert;
    return redirect("../../lancement-facture");
}

//var_dump($results);
$x = 1;

foreach ($results as $client) {
    //mise en forme du montant
    $montant_facture = round( (float) $client['total_facturation'] * 1.2, 2 ); // calcul de la tva: 20%
    if($montant_facture>0){
	    //remplace caractères spéciaux
	    $clientName = str_replace('&', 'et', $client['raison_social']);
	    // création de l'iban en retirant les espaces
	    $iban = trim($client['code_iban']) . trim($client['code_etablissement']) . trim($client['code_guichet']) . trim($client['num_compte']) . trim($client['rib']);
	
	    //@todo from AGU: contoller les données en entrée et en DB pour éviter le pansement try/catch
	    try {
	        $transaction = new SEPADirectDebitTransaction(); // (1..n)
	        $transaction->setEndToEndIdentification($client['code_client_hto']); // Vu par le débiteur
	        $transaction->setInstructedAmount($montant_facture);
	        $transaction->setMandateIdentification($client['code_client_hto']); // Vu par le débiteur
	        $transaction->setDateOfSignature(date("Y-m-d"));
	        //$transaction->setAmendmentIndicator('false');
	        $transaction->setDebtorName($clientName);
	        $transaction->setDebtorIban($iban);
	        $transaction->setDebtorAgentBIC($client['swift']);
	        $transaction->setRemittanceInformation("Facture " . date("d/m/Y")); // Vu par le débiteur
	        $paymentInfo->addTransaction($transaction);
	    } catch (Exception $exc) {
	        $logger->error('Erreur à la génération du fichier SEPA pour le client :' . $client['nom'] . '  Message : ' . $exc->getMessage());
	    }
	
	    $x++;
    }
}
$message->addPaymentInfo($paymentInfo);
//if ($message->validateXML('inc/SEPA2/validation_schemes/pain.008.003.02.xsd'))

header('Content-type: text/xml');
header('Content-Disposition: attachment; filename=' . date("Ymd") . '-SEPA.xml');

//maj nouveau client
if ($seqType === 'FRST') {
    $update = "UPDATE fiche_client SET nouveau_client = FALSE WHERE nouveau_client IS TRUE;";
}

$requete = $bdd->prepare($update);
$requete->execute();

echo $message->printXML();
?>
<?php

//redirect("../../lancement-facture");

}
else {
	redirect("home-admin");
}
?>  
